package com.lty.jeeg.server.modules.sys.controller;

import com.lty.jeeg.server.common.dto.ResponseInfo;
import com.lty.jeeg.server.common.utils.ResponseUtil;
import com.lty.jeeg.server.modules.sys.dao.RoleDao;
import com.lty.jeeg.server.modules.sys.dao.UserDao;
import com.lty.jeeg.server.common.dto.UserDto;
import com.lty.jeeg.server.modules.sys.model.Role;
import com.lty.jeeg.server.modules.sys.model.User;
import com.lty.jeeg.server.common.page.table.PageTableHandler;
import com.lty.jeeg.server.common.page.table.PageTableRequest;
import com.lty.jeeg.server.common.page.table.PageTableResponse;
import com.lty.jeeg.server.modules.sys.service.UserService;
import com.lty.jeeg.server.common.utils.UserUtil;
import com.lty.jeeg.server.modules.sys.service.impl.BaseService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.lty.jeeg.server.common.annotation.LogAnnotation;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.List;

/**
 * 用户相关接口
 * 
 * @author 小威老师 xiaoweijiagou@163.com
 *
 */
@Api(tags = "用户")

@RestController
@RequestMapping("/users")
public class UserController {

	private static final Logger log = LoggerFactory.getLogger("adminLogger");

	private final UserService userService;
	private final UserDao userDao;
	private final RoleDao roleDao;

    @Autowired
    public UserController(UserService userService, UserDao userDao, RoleDao roleDao) {
        this.userService = userService;
        this.userDao = userDao;
		this.roleDao = roleDao;
	}

    @LogAnnotation
	@PostMapping
	@ApiOperation(value = "保存用户")
	@RequiresPermissions("sys:user:add")
	public User saveUser(@RequestBody UserDto userDto) {
		User u = userService.getUser(userDto.getUsername());
		if (u != null) {
			throw new IllegalArgumentException(userDto.getUsername() + "已存在");
		}

		return userService.saveUser(userDto);
	}

	@LogAnnotation
	@PutMapping
	@ApiOperation(value = "修改用户")
	@RequiresPermissions("sys:user:add")
	public User updateUser(@RequestBody UserDto userDto) {
		return userService.updateUser(userDto);
	}

	@LogAnnotation
	@PutMapping(params = "headImgUrl")
	@ApiOperation(value = "修改头像")
	public void updateHeadImgUrl(String headImgUrl) {
		User user = UserUtil.getCurrentUser();
		UserDto userDto = new UserDto();
		// 不要拷贝全部属性，尤其是盐和密码
		userDto.setId(user.getId());
		userDto.setHeadImgUrl(headImgUrl);

		userService.updateUser(userDto);
		log.debug("{}修改了头像", user.getUsername());
	}

	@LogAnnotation
	@PutMapping("/{username}")
	@ApiOperation(value = "修改密码")
	public void changePassword(@PathVariable String username, String oldPassword, String newPassword) {
		userService.changePassword(username, oldPassword, newPassword);
	}

	@GetMapping
	@ApiOperation(value = "用户列表")
	public PageTableResponse listUsers(PageTableRequest request, @RequestParam(value = "isAll", required = false) Boolean isAll) {
		if (isAll != null && !isAll) {
			request.getParams().put("dsf", BaseService.dataScopeFilter("sys", UserUtil.getCurrentUser(), "d", "u"));
		}
		return new PageTableHandler(
				request1 -> userDao.count(request1.getParams()),
				request2 -> userDao.list(request2.getParams(),
						request2.getOffset(),
						request2.getLimit())
		).handle(request);
	}

	@ApiOperation(value = "当前登录用户")
	@GetMapping("/current")
	public User currentUser() {
		return userService.currentUser();
	}



	@ApiOperation(value = "根据用户id获取用户")
	@GetMapping("/{id}")
	public User user(@PathVariable Long id) {
		User user = userDao.getById(id);
		List<Role> roles = roleDao.listByUserId(id);
		user.setRoleList(roles);
		return user;
	}

	@LogAnnotation
	@DeleteMapping("/{id}")
	@ApiOperation(value = "删除用户")
	@RequiresPermissions(value = { "sys:user:del" })
	public void delete(@PathVariable Long id) {
		userService.delete(id);
	}

	@GetMapping("/listAll")
	@ApiOperation(value = "返回所有用户的JSONArray")
	public ResponseInfo listAll() {
		// TODO 放入缓存
		return ResponseUtil.success(userService.listAll());
	}
	@GetMapping("/partList/{id}")
	@ApiOperation(value = "返回部分用户的JSONArray")
	public ResponseInfo partList(@PathVariable Long id) {
		return ResponseUtil.success(userService.partList(id));
	}
}
